<?php

class InvoiceUnlocker
{

    public static function canRenderUnlockButton()
    {
        $user = Users::model()->findByPk(Yii::app()->user->id);
        return $user->checkPermission('invoices/UnlockInvoice');
    }

    public static function unlockInvoice($invoice)
    {
        if (self::canRenderUnlockButton())
        {
            $_SESSION['invoice-unlock'] = array(
                'invoice'   => $invoice,
                'view'      => 0
            );
        }
        else
        {
            if (isset($_SESSION['invoice-unlock']))
            {
                unset($_SESSION['invoice-unlock']);
            }
        }
    }

    public static function lockAllInvoice()
    {
        if (isset($_SESSION['invoice-unlock']))
        {
            unset($_SESSION['invoice-unlock']);
        }
    }

    public static function checkAndLockInvoice($invoice)
    {
        if (isset($_SESSION['invoice-unlock']))
        {
            if ($_SESSION['invoice-unlock']['invoice'] == $invoice && $_SESSION['invoice-unlock']['view'] >= 2)
            {
                unset($_SESSION['invoice-unlock']);
            }
        }
    }

    public static function increaseUnlockInvoiceViewCount($invoice)
    {
        if (isset($_SESSION['invoice-unlock']))
        {
            if ($_SESSION['invoice-unlock']['invoice'] == $invoice)
            {
                $_SESSION['invoice-unlock']['view']++;
                if ($_SESSION['invoice-unlock']['view'] >= 2)
                {
                    unset($_SERVER['invoice-unlock']);
                }
            }
        }
    }

    public static function isInvoiceUnlocked($invoice)
    {
        if (isset($_SESSION['invoice-unlock']))
        {
            if ($_SESSION['invoice-unlock']['invoice'] == $invoice && $_SESSION['invoice-unlock']['view'] < 2)
            {
                return true;
            }
            else
            {
                
            }
        }
        return false;
    }

}

?>
